<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    function Promise(executor){

        //保存回调函数
        this.callback={};

        this.PromiseState='pending';
        this.PromiseResult=null;

        const self=this;

        //成功回调函数
        function resolve(data){
            //状态只能修改一次
            if(self.PromiseState!=='pending') return;

            self.PromiseState='fulfilled';
            self.PromiseResult=data;

            //如果有回调函数   调用回调函数
            if(self.callback.onResolved){
                self.callback.onResolved(data)
            }
        }

        //失败回调函数
        function reject(data){
            if(self.PromiseState!=='pending') return;
            self.PromiseState='rejected';
            self.PromiseResult=data;


            //调用回调函数
            if(self.callback.onRejected){
                self.callback.onRejected(data)
            }
        }


        //捕捉异常
        try {
            //同步调用 执行器函数
            executor(resolve, reject);
        } catch (e) {
            reject(e)
        }
    }

    Promise.prototype.then=function (onResolved,onRejected){



        //回调函数
        /*  onResolved=  function (value){
                 console.log(value)
                                }*/
        if(this.PromiseState==='fulfilled'){
            onResolved(this.PromiseResult);
        }


        if(this.PromiseState==='rejected'){
            onRejected(this.PromiseResult);
        }



        //保存回调函数
        if(this.PromiseState==='pending'){
            this.callback={
                'onResolved':onResolved,
                'onRejected':onRejected
            }
        }

    }


    let p=new Promise(function (resolve,reject){

        setTimeout(function (){
       //     resolve('ok');
            reject('error')
        },2000)

    });

    console.log(p)

    p.then(function (success){
        console.log(success)
    },function (fail){
        console.log(fail)
    })


</script>
</body>
</html>